package com.ayoka.parenting.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import com.jincp.common.utils.DateUtil;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.StringUtil;

import java.util.Observable;
import java.util.Observer;


/**
 * Created by Stone on 2015/8/22.
 * Project:TimeDemo
 * Company:Pactera
 * Email:chenxi304102067@gmail.com
 */
public class MyCountDownTextView extends AppCompatTextView implements Observer {

    private long endMilliSeconds;
    private String format = "%s";
    private CountDownListener countDownListener;

    public MyCountDownTextView(Context context) {
        super(context);
    }

    public MyCountDownTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setEndMilliSeconds(long endMilliSeconds) {
        setEndMilliSeconds(format, endMilliSeconds, null);
    }

    public void setEndMilliSeconds(String format, long endMilliSeconds, CountDownListener countDownListener) {
        this.format = format;
        this.endMilliSeconds = endMilliSeconds;
        this.countDownListener = countDownListener;
        MyCountDownTimer.getInstance().addObserver(this);
    }


    @Override
    public void update(Observable observable, Object arg) {
        if (observable instanceof MyCountDownTimer) {
            long currentMillis = (long) arg;
            onTimeUpdated(currentMillis);
        }
    }

    private void onTimeUpdated(long currentMilliseconds) {
        long leftMilliseconds = endMilliSeconds - currentMilliseconds;
        if (leftMilliseconds > 0) {
            setText(StringUtil.formatString(format, DateUtil.formatTime(leftMilliseconds / 1000)));
        } else if (leftMilliseconds <= 0) {
            setText(StringUtil.formatString(format, DateUtil.formatTime(0)));
        }
        if (countDownListener != null) {
            countDownListener.onTick(leftMilliseconds);
        }
        if (leftMilliseconds <= 0) {
            MyCountDownTimer.getInstance().deleteObserver(this);
            countDownListener = null;
        }
    }

    public interface CountDownListener{
        void onTick(long leftMilliseconds);
    }
}
